package com.example.juc.kingdom_adventures.term6;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Client1 {
    private int number = 0;
    private final ReentrantLock lock = new ReentrantLock();

    private void write(int change) {
        lock.lock();
        number += change;
        lock.unlock();
    }

    /**
     * ReentrantLock 的优势在于，它可以设置尝试获取锁的等待时间，超过等待时间便不再尝试获取锁
     * ReentrantLock 比 synchronized 更安全，可以完全避免无限等待
     *
     * @param change
     * @throws InterruptedException
     */
    private void write1(int change) throws InterruptedException {
        if (lock.tryLock(1, TimeUnit.SECONDS)) {
            number += change;
            lock.unlock();
        } else {
            System.out.println("1 秒内没有获取到锁，不再等待。");
        }
    }
}
